<template>
  <div>
    <el-input v-model="name"
              :size="size"
              suffix-icon="el-icon-user"
              placeholder="人员选择"
              readonly
              :disabled="disabled"
              @click.native="handleSelect"></el-input>
    <el-dialog ref="wf-dialog"
               custom-class="wf-dialog"
               :visible.sync="visible"
               title="人员选择"
               width="60%"
               :before-close="handleClose"
               append-to-body>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 v-model="form"
                 ref="crud"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionList=$event"
                 @current-change="page.currentPage=$event"
                 @size-change="page.pageSize=$event"
                 @row-click="rowClick"
                 @on-load="onLoad">
        <template v-if="checkType == 'radio'"
                  #radio="{row}">
          <el-radio v-model="form.radio"
                    :label="row.id"><i></i></el-radio>
        </template>
      </avue-crud>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="handleClose"
                   size="mini">取 消</el-button>
        <el-button type="primary"
                   @click="handleConfirm"
                   size="mini">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<script>
export default {
  name: 'user-select',
  props: {
    value: [String, Number],
    checkType: { // radio单选 checkbox多选
      type: String,
      default: () => {
        return 'radio'
      }
    },
    size: {
      type: String,
      default: () => {
        return 'small'
      }
    },
    readonly: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val) this.changeDefaultChecked()
      },
      immediate: true
    },
    checkType: {
      handler(val) {
        if (val == 'radio') {
          this.$set(this.option, 'selection', false)
          this.findObject(this.option.column, 'radio').hide = false
        } else {
          this.$set(this.option, 'selection', true)
          this.findObject(this.option.column, 'radio').hide = true
        }
      },
      immediate: true
    }
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    names() {
      let names = [];
      this.selectionList.forEach(ele => {
        names.push(ele.realName);
      });
      return names.join(",");
    }
  },
  data() {
    return {
      visible: false,
      name: '',
      form: {},
      query: {},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      data: [],
      option: {
        size: 'mini',
        searchSize: 'mini',
        align: 'center',
        menu: false,
        addBtn: false,
        header: false,
        border: true,
        tip: false,
        reserveSelection: true,
        highlightCurrentRow: true,
        gutter: 5,
        searchMenuSpan: 6,
        selection: true,
        column: [{
          label: '',
          prop: 'radio',
          type: 'radio',
          width: 55,
          hide: true
        }, {
          label: '头像',
          prop: 'avatar',
          type: 'upload',
          width: 90
        }, {
          label: '姓名',
          prop: 'name',
          overHidden: true,
          search: true
        }, {
          label: '部门',
          prop: 'deptName',
          overHidden: true,
          search: true
        }, {
          label: '职位',
          prop: 'postName',
          overHidden: true,
          search: true
        }]
      }
    }
  },
  mounted() {
    this.onLoad(this.page).then(() => {
      this.changeDefaultChecked()
    })
  },
  methods: {
    handleSelect() {
      if (this.readonly || this.disabled) return
      else this.visible = true
    },
    handleConfirm() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据")
        return
      }
      this.$set(this, 'name', this.names)
      this.$emit('input', this.ids)
      this.handleClose()
    },
    handleClose(done) {
      // this.selectionClear()
      this.visible = false
      if (done && typeof done == 'function') done()
    },
    searchReset() {
      this.query = {}
      this.onLoad(this.page)
    },
    searchChange(params, done) {
      this.query = params
      this.page.currentPage = 1
      this.onLoad(this.page, params)
      done()
    },
    selectionClear() {
      this.selectionList = []
      if (this.$refs.crud) this.$refs.crud.toggleSelection()
    },
    rowClick(row) {
      if (this.checkType == 'radio') {
        this.selectionList = [row]
        this.$set(this.form, 'radio', row.id)
      } else this.$refs.crud.toggleSelection([row])
    },
    changeDefaultChecked() {
      if (!this.value) return
      let defaultChecked = this.value + ''

      const name = []
      if (this.checkType == 'checkbox') {
        this.selectionClear()
        const checks = defaultChecked.split(",")
        if (checks.length > 0) {
          setTimeout(() => {
            checks.forEach(c => {
              const row = this.data.find(d => d.id == c)
              if (row) name.push(row.realName)
              if (row && this.$refs.crud) {
                this.$refs.crud.toggleRowSelection(row, true)
              }
            })
          }, 500);
        }
      } else {
        const row = this.data.find(d => d.id == defaultChecked)
        if (row) {
          this.selectionList = [row]
          this.$set(this.form, 'radio', defaultChecked)
          name.push(row.realName)
        } else {
          this.selectionList = []
          this.$set(this.form, 'radio', '')
        }
      }
      setTimeout(() => {
        this.$set(this, 'name', name.join(','))
      }, 1000);
    },
    onLoad(page, params = {}) {
      return new Promise((resolve) => {
        this.loading = true;
        const param = {
          current: page.currentPage,
          size: page.pageSize,
          ...Object.assign(params, this.query)
        }
        this.$axios.get('/api/blade-user/search/user', { params: param }).then(res => {
          this.page.total = res.data.data.total
          this.data = res.data.data.records
          this.loading = false
          resolve()
        })
      })
    },
  }
}
</script>
<style lang="scss">
.wf-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -40%);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
  .el-dialog__body {
    flex: 1;
    overflow: auto;
  }
}
</style>